package com.jiangnan.ui.activity

import android.net.Uri
import android.os.Bundle
import android.text.Editable
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.jiangnan.R
import com.jiangnan.databinding.ActivityMyBinding
import com.jiangnan.entity.LoginInfo
import com.jiangnan.util.CurrentHolder
import com.jiangnan.util.CurrentLoginInfo
import com.jiangnan.util.GlideUtil
import com.jiangnan.util.SharedPrefUtil
import com.jiangnan.util.ToastUtil
import com.jiangnan.viewmodel.UserViewModel
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.toRequestBody

class MyActivity : BaseActivity(), View.OnClickListener {

    private lateinit var binding : ActivityMyBinding
    private lateinit var userViewModel: UserViewModel
    private var currentUserId : Int? = null
    private var currentLoginInfo : LoginInfo? = null
    private var selectedUri: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 启用边缘到边缘 沉浸式布局
        enableEdgeToEdge()
        binding = DataBindingUtil.setContentView(this, R.layout.activity_my)
        userViewModel = ViewModelProvider(this).get(UserViewModel::class.java)

        SharedPrefUtil.getLoginInfo(this).let {
            currentUserId = it!!.id
            currentLoginInfo = it
        }
//        currentUserId = CurrentLoginInfo.getCurrentLoginInfo()!!.id
//        currentLoginInfo = CurrentLoginInfo.getCurrentLoginInfo()

        initUI()
        setOnClock()
        initObserve()
    }

    private fun initObserve() {
        /**
         * 监听toast消息
         */
        userViewModel.toastMessage.observe(this){
            ToastUtil.showShort(this, it)
        }
        /**
         * 监听上传头像的相应
         */
        userViewModel.avatarUrl.observe(this){
            GlideUtil.loadImageWithPlaceholder(
                this,
                it,
                R.drawable.img_default,
                R.drawable.img_error,
                binding.ivUserAvatar
            )
            selectedUri = it
        }
        /**
         * 监听修改用户信息的相应
         */
        userViewModel.updateUserInfoResponse.observe(this){
            // 删除之前的 ThreadLocal
//            CurrentHolder.remove()
//            CurrentHolder.setCurrentLoginInfo(currentLoginInfo!!)
            SharedPrefUtil.saveLoginInfo(this, currentLoginInfo!!)
        }

    }

    private fun setOnClock() {
        binding.btnUserSubmit.setOnClickListener(this)
        binding.btnUploadAvator.setOnClickListener(this)
    }

    private fun initUI() {
        /**
         * 头像
         */
        GlideUtil.loadImageWithPlaceholder(
            this,
            currentLoginInfo!!.avatar,
            R.drawable.img_default,
            R.drawable.img_error,
            binding.ivUserAvatar
        )
        // 昵称
        binding.etUserNickname.setText(currentLoginInfo!!.nickname)
        // 性别
        when (currentLoginInfo!!.gender) {
            0 -> binding.etUserGender.setText("未指定")
            1 -> binding.etUserGender.setText("男士")
            2 -> binding.etUserGender.setText("女士")
        }
        // 个性签名
        binding.etUserLocale.setText(currentLoginInfo!!.locale)
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.btn_user_submit -> {
                // 修改昵称
                currentLoginInfo!!.nickname = binding.etUserNickname.text.toString()
                // 修改性别
                when (binding.etUserGender.text.toString()) {
                    "0" -> currentLoginInfo!!.gender = 0
                    "1" -> currentLoginInfo!!.gender = 1
                    "2" -> currentLoginInfo!!.gender = 2
                }
                if (selectedUri != null) {
                    // 上传头像
                    currentLoginInfo!!.avatar = selectedUri!!
                }
                // 修改签名
                currentLoginInfo!!.locale = binding.etUserLocale.text.toString()
                userViewModel.updateUserInfo(currentUserId!!, currentLoginInfo!!)
//                CurrentLoginInfo.setCurrentLoginInfo(currentLoginInfo!!)
                SharedPrefUtil.saveLoginInfo(this, currentLoginInfo!!)

            }
            R.id.btn_upload_avator -> {
                // 上传头像
                getImageContent.launch("image/*")
                ToastUtil.showShort(this,"点击了上传按钮")
            }
         }
    }

    // 注册图片选择回调
    private val getImageContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
        uri?.let { selectedUri ->
            // 从内容解析器中读取图片数据
            contentResolver.openInputStream(selectedUri)?.use { inputStream ->
                val bytes = inputStream.readBytes()
                // 构建 RequestBody（图片类型）
                val requestBody = bytes.toRequestBody("image/*".toMediaTypeOrNull())
                // 构造一个文件名，例如：cover_时间戳.jpg
                val fileName = "cover_${System.currentTimeMillis()}.jpg"
                // 构造 MultipartBody.Part 对象，字段名需和后端接收一致，这里假设为 "file"
                val part = MultipartBody.Part.createFormData("file", fileName, requestBody)
                // 调用 ViewModel 上传方法
                userViewModel.uploadAvatarImage(part)
            }
        }
    }
}